// FoodPage.tsx
import React, { useState, useEffect, useRef } from 'react';
import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonSearchbar,
  IonGrid,
  IonRow,
  IonCol,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardSubtitle,
  IonCardTitle,
  IonChip,
  IonLabel,
  IonIcon,
  IonBadge,
  IonSegment,
  IonSegmentButton,
  IonButtons,
  IonButton,
  IonMenuButton,
  IonRefresher,
  IonRefresherContent,
  IonInfiniteScroll,
  IonInfiniteScrollContent,
  IonSpinner,
  IonAlert
} from '@ionic/react';
import { 
  star, 
  time, 
  flame, 
  cart, 
  heart, 
  heartOutline,
  filter,
  menu
} from 'ionicons/icons';
import './FoodPage.css';
import { FoodItem } from '../../models/FoodItem';
import FoodCard from './FoodCard';
import { FoodCategory } from '../../models/FoodCategory';


const FoodPage: React.FC = () => {
  // 状态管理
  const [categories, setCategories] = useState<FoodCategory[]>([]);
  const [foodItems, setFoodItems] = useState<FoodItem[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<number>(1);
  const [searchText, setSearchText] = useState<string>('');
  const [filteredFoods, setFilteredFoods] = useState<FoodItem[]>([]);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [favorites, setFavorites] = useState<number[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [showAlert, setShowAlert] = useState<boolean>(false);
  const [selectedFood, setSelectedFood] = useState<FoodItem | null>(null);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const itemsPerPage = 8;

  const contentRef = useRef<HTMLIonContentElement>(null);

  // 模拟数据
  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    setLoading(true);
    
    // 模拟 API 调用延迟
    setTimeout(() => {
      // 分类数据
      const mockCategories: FoodCategory[] = [
        { id: 1, name: '全部', icon: '🍽️', count: 28 },
        { id: 2, name: '中餐', icon: '🥢', count: 12 },
        { id: 3, name: '西餐', icon: '🍕', count: 8 },
        { id: 4, name: '日料', icon: '🍣', count: 6 },
        { id: 5, name: '甜点', icon: '🍰', count: 10 },
        { id: 6, name: '饮品', icon: '🥤', count: 15 },
        { id: 7, name: '快餐', icon: '🍔', count: 9 },
        { id: 8, name: '素食', icon: '🥗', count: 7 },
      ];

      // 美食数据
      const mockFoodItems: FoodItem[] = [
        {
          id: 1,
          name: '北京烤鸭',
          description: '传统北京风味烤鸭，皮脆肉嫩，配以薄饼和甜面酱',
          price: 128,
          rating: 4.8,
          prepTime: 30,
          calories: 450,
          image: 'https://images.unsplash.com/photo-1544025162-d76694265947?w=300&h=200&fit=crop',
          categoryId: 2,
          isFeatured: true,
          tags: ['热门', '招牌']
        },
        {
          id: 2,
          name: '意大利面',
          description: '经典番茄意大利面，配新鲜罗勒和帕玛森奶酪',
          price: 68,
          rating: 4.5,
          prepTime: 20,
          calories: 320,
          image: 'https://images.unsplash.com/photo-1598866594230-a7c12756260f?w=300&h=200&fit=crop',
          categoryId: 3,
          tags: ['西式', '经典']
        },
        {
          id: 3,
          name: '寿司拼盘',
          description: '新鲜三文鱼寿司组合，包含多种口味',
          price: 98,
          rating: 4.7,
          prepTime: 15,
          calories: 280,
          image: 'https://images.unsplash.com/photo-1579584425555-c3ce17fd4351?w=300&h=200&fit=crop',
          categoryId: 4,
          isFeatured: true,
          tags: ['日式', '海鲜']
        },
        {
          id: 4,
          name: '提拉米苏',
          description: '意式经典甜点，咖啡与马斯卡彭的完美结合',
          price: 38,
          rating: 4.6,
          prepTime: 10,
          calories: 180,
          image: 'https://images.unsplash.com/photo-1571877227200-a0d98ea607e9?w=300&h=200&fit=crop',
          categoryId: 5,
          tags: ['甜点', '意式']
        },
        {
          id: 5,
          name: '珍珠奶茶',
          description: '台湾特色奶茶，Q弹珍珠搭配香浓奶茶',
          price: 25,
          rating: 4.4,
          prepTime: 5,
          calories: 120,
          image: 'https://images.unsplash.com/photo-1568649929103-28ffbefaca1e?w=300&h=200&fit=crop',
          categoryId: 6,
          tags: ['饮品', '台湾']
        },
        {
          id: 6,
          name: '汉堡套餐',
          description: '牛肉汉堡配薯条和可乐，经典美式风味',
          price: 45,
          rating: 4.3,
          prepTime: 12,
          calories: 380,
          image: 'https://images.unsplash.com/photo-1571091718767-18b5b1457add?w=300&h=200&fit=crop',
          categoryId: 7,
          tags: ['快餐', '美式']
        },
        {
          id: 7,
          name: '蔬菜沙拉',
          description: '新鲜有机蔬菜沙拉，配特调酱汁',
          price: 32,
          rating: 4.2,
          prepTime: 8,
          calories: 90,
          image: 'https://images.unsplash.com/photo-1512621776951-a57141f2eefd?w=300&h=200&fit=crop',
          categoryId: 8,
          isVeg: true,
          tags: ['健康', '素食']
        },
        {
          id: 8,
          name: '麻辣香锅',
          description: '四川特色麻辣香锅，多种食材可选',
          price: 78,
          rating: 4.7,
          prepTime: 25,
          calories: 420,
          image: 'https://images.unsplash.com/photo-1585032226651-759b368d7246?w=300&h=200&fit=crop',
          categoryId: 2,
          isFeatured: true,
          tags: ['川菜', '麻辣']
        },
        {
          id: 9,
          name: '披萨',
          description: '意式薄底披萨，多种 toppings 可选',
          price: 89,
          rating: 4.5,
          prepTime: 18,
          calories: 350,
          image: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?w=300&h=200&fit=crop',
          categoryId: 3,
          tags: ['西式', '意式']
        },
        {
          id: 10,
          name: '抹茶拿铁',
          description: '日式抹茶与牛奶的完美融合',
          price: 32,
          rating: 4.6,
          prepTime: 6,
          calories: 110,
          image: 'https://images.unsplash.com/photo-1515823064-d6e0c04616a7?w=300&h=200&fit=crop',
          categoryId: 6,
          tags: ['饮品', '日式']
        }
      ];

      setCategories(mockCategories);
      setFoodItems(mockFoodItems);
      setFilteredFoods(mockFoodItems);
      setLoading(false);
    }, 1000);
  };

  // 过滤美食数据
  useEffect(() => {
    let filtered = foodItems;

    // 按分类过滤
    if (selectedCategory !== 1) {
      filtered = filtered.filter(item => item.categoryId === selectedCategory);
    }

    // 按搜索文本过滤
    if (searchText) {
      filtered = filtered.filter(item =>
        item.name.toLowerCase().includes(searchText.toLowerCase()) ||
        item.description.toLowerCase().includes(searchText.toLowerCase()) ||
        item.tags?.some(tag => tag.toLowerCase().includes(searchText.toLowerCase()))
      );
    }

    setFilteredFoods(filtered);
    setCurrentPage(1);
  }, [selectedCategory, searchText, foodItems]);

  // 处理刷新
  const handleRefresh = (event: any) => {
    setTimeout(() => {
      loadData();
      event.detail.complete();
    }, 2000);
  };

  // 处理无限滚动
  const loadMore = (event: any) => {
    setTimeout(() => {
      setCurrentPage(prev => prev + 1);
      event.target.complete();
    }, 1000);
  };

  // 切换收藏
  const toggleFavorite = (foodId: number) => {
    setFavorites(prev => 
      prev.includes(foodId) 
        ? prev.filter(id => id !== foodId)
        : [...prev, foodId]
    );
  };

  // 添加到购物车
  const addToCart = (food: FoodItem) => {
    setSelectedFood(food);
    setShowAlert(true);
  };

  const inFavorites = (id:number)  => {
    return favorites.includes(id)
  }

  // 获取当前页面的美食
  const getCurrentPageFoods = () => {
    const startIndex = 0;
    const endIndex = currentPage * itemsPerPage;
    return filteredFoods.slice(startIndex, endIndex);
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle>美食天堂</IonTitle>
          <IonButtons slot="end">
            <IonButton onClick={() => setViewMode(viewMode === 'grid' ? 'list' : 'grid')}>
              <IonIcon icon={viewMode === 'grid' ? menu : filter} />
            </IonButton>
          </IonButtons>
        </IonToolbar>

        {/* 搜索栏 */}
        <IonToolbar>
          <IonSearchbar
            value={searchText}
            onIonInput={(e) => setSearchText(e.detail.value!)}
            placeholder="搜索美食、分类、标签..."
            animated
            className="search-bar"
          />
        </IonToolbar>


      </IonHeader>

      <IonContent fullscreen ref={contentRef}>
        <IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
          <IonRefresherContent></IonRefresherContent>
        </IonRefresher>

        <div className="food-page-container">
          {/* 桌面端布局 */}
          <div className="desktop-layout">
            <IonGrid fixed>
              <IonRow>
                {/* 左侧分类列表 - 桌面端 */}
                <IonCol size-lg="3" size-md="4" className="mobile-categories">
                  <div className="categories-sidebar">
                    <h3>美食分类</h3>
                    {categories.map(category => (
                      <div
                        key={category.id}
                        className={`category-item ${selectedCategory === category.id ? 'active' : ''}`}
                        onClick={() => setSelectedCategory(category.id)}
                      >
                        <div className="category-info">
                          <span className="category-icon">{category.icon}</span>
                          <span className="category-name">{category.name}</span>
                        </div>
                        {category.count && (
                          <IonBadge color="light" className="category-count">
                            {category.count}
                          </IonBadge>
                        )}
                      </div>
                    ))}
                  </div>
                </IonCol>

                {/* 右侧内容区域 */}
                <IonCol size-lg="9" size-md="8">
                  {/* 视图模式切换 - 桌面端 */}
                  <div className="view-controls">
                    <div className="results-count">
                      找到 {filteredFoods.length} 个结果
                    </div>
                    <div className="view-toggle">
                      <IonButton
                        fill={viewMode === 'grid' ? 'solid' : 'outline'}
                        size="small"
                        onClick={() => setViewMode('grid')}
                      >
                        网格
                      </IonButton>
                      <IonButton
                        fill={viewMode === 'list' ? 'solid' : 'outline'}
                        size="small"
                        onClick={() => setViewMode('list')}
                      >
                        列表
                      </IonButton>
                    </div>
                  </div>

                  {/* 加载状态 */}
                  {loading && (
                    <div className="loading-container">
                      <IonSpinner name="crescent" />
                      <p>加载中...</p>
                    </div>
                  )}

                  {/* 美食列表 */}
                  {!loading && (
                    <div className={`foods-container ${viewMode}-view`}>
                      {getCurrentPageFoods().map(food => (
                        <FoodCard food={food} setFavorite={toggleFavorite} addToCart={addToCart} inFavorites={inFavorites} />
                      ))}
                    </div>
                  )}

                  {/* 空状态 */}
                  {!loading && getCurrentPageFoods().length === 0 && (
                    <div className="empty-state">
                      <div className="empty-icon">🍽️</div>
                      <h3>暂无美食</h3>
                      <p>换个搜索词或分类试试吧</p>
                      <IonButton onClick={() => {
                        setSearchText('');
                        setSelectedCategory(1);
                      }}>
                        查看全部美食
                      </IonButton>
                    </div>
                  )}

                  {/* 无限滚动 */}
                  {getCurrentPageFoods().length > 0 && getCurrentPageFoods().length < filteredFoods.length && (
                    <IonInfiniteScroll onIonInfinite={loadMore}>
                      <IonInfiniteScrollContent
                        loadingSpinner="bubbles"
                        loadingText="加载更多美食..."
                      ></IonInfiniteScrollContent>
                    </IonInfiniteScroll>
                  )}
                </IonCol>
              </IonRow>
            </IonGrid>
          </div>
        </div>
      </IonContent>

      {/* 添加到购物车确认弹窗 */}
      <IonAlert
        isOpen={showAlert}
        onDidDismiss={() => setShowAlert(false)}
        header={'添加到购物车'}
        message={`确定要将 ${selectedFood?.name} 添加到购物车吗？`}
        buttons={[
          '取消',
          {
            text: '确定',
            handler: () => {
              console.log('添加到购物车:', selectedFood);
            }
          }
        ]}
      />
    </IonPage>
  );
};

export default FoodPage;